﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    var appView = Windows.UI.ViewManagement.ApplicationView;
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var nav = WinJS.Navigation;
    var ui = WinJS.UI;
    var utils = WinJS.Utilities;

    WinJS.UI.Pages.define("/pages/register/register.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // Store useful things.
            var merchantId = options.merchantId;
            $("#emailEditText2").val(options.email).attr("readonly", "readonly");

            // Add click handler to registerButton.
            $("#registerButton").click(function () {
                if (validateForm()) {
                    registerAccount(merchantId);
                }                
            });
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            /// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
            /// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />

            // TODO: Respond to changes in viewState.
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        }
    });

    function validateForm() {
        var password = $("#passwordEditText2").val();
        var passwordConfirm = $("#passwordConfirmEditText").val();

        if (password == "") {
            $("#messagePanel2").text("Please enter your password.");
            return false;
        }

        if (password.length < 4) {
            $("#messagePanel2").text("The Password field must be at least 4 characters in length.");
            return false;
        }

        if (passwordConfirm == "") {
            $("#messagePanel2").text("Please confirm your password.");
            return false;
        }

        if (password != passwordConfirm) {
            $("#messagePanel2").text("Your password entries must match. Please try again.");
            return false;
        }

        return true;
    }

    function registerAccount(merchantId) {
        var email = $("#emailEditText2").val();
        var password = $("#passwordEditText2").val();

        // Prepare params.
        var dataJson = { email: email, password: password, merchant_id: merchantId };
        
        // Register new account and claim a merchant. (API #5)
        WinJS.xhr({
            url: HOST_NAME + "/register",
            type: "post",
            data: formatParams(dataJson),
            headers: { "Content-type": "application/x-www-form-urlencoded" }
        }).then(
            function onComplete(result) {
                // Check if API call is successful.
                if (result.status === 200) {
                    console.log(result.responseText);

                    // Parse xhr to JSON.
                    var response = JSON.parse(result.response);
                    var isSuccessful = response.is_execution_successful;

                    // Check result code.
                    if (isSuccessful == true) {
                        var userId = response.user_id;
                        // Go to SelectTipId screen.
                        nav.navigate("/pages/selectTipId/selectTipId.html", { userId: userId, email: email, merchantId: merchantId });
                    } else {
                        var executionCode = response.execution_code;
                        if (executionCode == "FAILURE__EMAIL_REGISTRATION__ALREADY_REGISTERED") {
                            $("#messagePanel2").text("This account has already been registered.");
                        } else {
                            $("#messagePanel2").text("Register failed.");
                        }
                    }
                }
            },
            function onError(error) {
                console.log("registerAccount::error: " + error.message);
            }
        )
    }
})();
